package com.huanxing.cloud.miniapp.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huanxing.cloud.common.core.constant.CacheConstants;
import com.huanxing.cloud.common.core.desensitization.KeyDesensitization;
import com.huanxing.cloud.common.core.util.Result;
import com.huanxing.cloud.common.security.handler.HxBusinessException;
import com.huanxing.cloud.miniapp.api.dto.WxQrCodeDTO;
import com.huanxing.cloud.miniapp.api.entity.WxApp;
import com.huanxing.cloud.miniapp.api.vo.WxAppV0;
import com.huanxing.cloud.miniapp.config.WxMaConfiguration;
import com.huanxing.cloud.miniapp.mapper.WxAppMapper;
import com.huanxing.cloud.miniapp.service.IWxAppService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.util.Base64;

/**
 * 微信应用
 *
 * @author lijx
 * @since 2022/2/26 16:37
 */
@Service
public class WxAppServiceImpl extends ServiceImpl<WxAppMapper, WxApp> implements IWxAppService {

	private final KeyDesensitization keyDesensitization = new KeyDesensitization();

	@Override
	public WxApp findByAppId(String appId) {
		return baseMapper.selectByAppId(appId);
	}

	@Override
	public IPage<WxAppV0> getPage(Page page, WxApp wxApp) {
		return baseMapper.selectWxAppPage(page, wxApp);
	}

	@Override
	public WxAppV0 getWxAppById(String appId) {
		return baseMapper.selectWxAppByAppId(appId);
	}

	@Override
	public String createWxaCodeUnlimit(WxQrCodeDTO wxQrCodeDTO) {
		final WxMaService wxService = WxMaConfiguration.getMaService(wxQrCodeDTO.getAppId());
		try {
			File file = wxService.getQrcodeService()
				.createWxaCodeUnlimit(wxQrCodeDTO.getScene(), wxQrCodeDTO.getPage(), true, wxQrCodeDTO.getEnvVersion(),
						120, false, null, false);
			FileInputStream fileInputStream = new FileInputStream(file);
			byte[] buffer = new byte[(int) file.length()];
			fileInputStream.read(buffer);
			fileInputStream.close();
			String rsEncode = new String(Base64.getEncoder().encode(buffer));
			return rsEncode;
		}
		catch (Exception e) {
			throw new HxBusinessException(e.getMessage());
		}
	}

	@Override
	@CacheEvict(value = CacheConstants.WX_APP_CACHE, key = "#wxApp.appId", allEntries = true)
	public Boolean updateWxAppById(WxApp wxApp) {
		WxApp target = baseMapper.selectById(wxApp.getAppId());
		if (keyDesensitization.serialize(target.getAppSecret()).equals(wxApp.getAppSecret())) {
			wxApp.setAppSecret(null);
		}
		return this.updateById(wxApp);
	}

}
